package com.bwie.task;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bwie.es.EsProd;
import com.bwie.mapper.TbProdMapper;
import com.bwie.pojo.TbProd;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.IndexOperations;
import org.springframework.data.elasticsearch.core.document.Document;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @description :
 * @Author QiHainan
 * @Create 2025/6/30 21:16
 * @Version 1.0
 */
@Component
public class SyncProdTask {

    @Autowired
    ElasticsearchRestTemplate elasticsearchRestTemplate;
    @Autowired
    TbProdMapper tbProdMapper;

    @Scheduled(cron = "0 0/1 * * * ?")
    public void syncProdTask(){
        System.out.println("开始加载");

        IndexOperations indexOps = elasticsearchRestTemplate.indexOps(EsProd.class);
        boolean exists = indexOps.exists();

        if(exists){
            indexOps.delete();

            indexOps.create();

            Document mapping = indexOps.createMapping();
            indexOps.putMapping(mapping);
        }

        Page<TbProd> page = new Page<>(1, 99999);

        Page<TbProd> tbProdList = tbProdMapper.getProdList(page,null);
        for (TbProd tbProd : tbProdList.getRecords()) {
            EsProd esProd = BeanUtil.toBean(tbProd, EsProd.class);
            elasticsearchRestTemplate.save(esProd);
        }

        System.out.println("任务结束");
    }

}
